#!/usr/bin/env perl
use warnings;
use strict;

# define error constants
use constant BAD_CREDS     => 0;
use constant ACCESS_DENIED => 1;
use constant BAD_FILE      => 2;
use constant DUPE_FILE     => 3;
use constant BAD_CGI       => 4;
use constant DUPE_NAME     => 5;

### html display functions ###
sub html_begin() {
    print <<END;
Content-Type: text/html; charset=utf-8
Pragma: no-cache

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
END
}

sub html_title($) {
    my ($title) = @_;

    print "        <title>$title</title>\n";
}

sub html_css(@) {
    my (@css) = @_;

    foreach (@css) {
        print '        <link rel="stylesheet" type="text/css" href="' .
              $_ . "\" />\n";
    }
}

sub html_body() {
    print "    </head>\n\n    <body>\n";
}

sub html_end() {
    print "    </body>\n</html>\n";
}

# handle an error by printing the associated message and exiting program
sub error($) {
    my ($reason) = @_;

    html_begin();
    html_title("Error");
    html_body();

    my ($h, $p);
    if ($reason == ACCESS_DENIED) {
        $h = "Access Denied";
        $p = "You are not authorized to view this file or directory.";
    }
    elsif ($reason == BAD_CREDS) {
        $h = "Bad Credentials";
        $p = "You have supplied bad credentials.";
    }
    elsif ($reason == BAD_FILE) {
        $h = "Bad File";
        $p = "Your uploaded file was rejected by the server.";
    }
    elsif ($reason == DUPE_FILE) {
        $h = "Duplicate File";
        $p = "Your uploaded file already exists on the server.";
    }
    elsif ($reason == BAD_CGI) {
        $h = "Bad CGI";
        $p = "You have given a bad set of CGI parameters.";
    }
    elsif ($reason == DUPE_NAME) {
        $h = "Duplicate Filename";
        $p = "A file with that name already exists.";
    }
    else {
        $h = "Unknown Error";
        $p = "An unknown error has occured.";
    }

    print "        <h1>$h</h1>\n        <p>$p</p>\n";

    html_end();
    exit;
}

# transform a filesize (in bytes) into appropriate B/kiB/MiB/GiB measurement
sub pretty_size($) {
    my ($size) = @_;
    my $ret = '';

    # make sure we were passed an actual size
    if ($size !~ /^[0-9]+$/) {
        return 'NaN';
    }

    if ($size < 1024) {
        $ret = sprintf("%d B", $size);
    }
    elsif ($size < 1048576) {
        $size /= 1024;
        $ret = sprintf("%.2f kiB", $size);
    }
    elsif ($size < 1073741824) {
        $size /= 1048576;
        $ret = sprintf("%.2f MiB", $size);
    }
    else {
        $size /= 1073741824;
        $ret = sprintf("%.2f GiB", $size);
    }

    return $ret;
}

1;
